<template>
  <el-card style="height: 70px">
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称">
        <el-input placeholder="请输入搜索词" v-model="keyWord"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getRoleList()">搜索</el-button>
        <el-button type="primary" @click="reSet">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 20px 0px">
    <el-button type="primary" icon="Plus" @click="addRole">添加角色</el-button>

    <el-table border :data="roleList" style="margin: 20px 0px">
      <el-table-column
        label="#"
        type="index"
        align="center"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="id"
        align="center"
        width="80px"
        prop="id"
      ></el-table-column>
      <el-table-column label="名称" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="修改时间" prop="updateTime"></el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Menu"
            @click="updateMenu(row.id)"
          >
            分配菜单
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`您确定删除${row.roleName}吗？`"
            @confirm="remove(row.id)"
            width="200px"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getRoleList"
    />
  </el-card>

  <el-dialog
    v-model="dialog"
    :title="roleForm.id ? '编辑角色' : '新增角色'"
    width="30%"
  >
    <el-form :rules="rules" :model="roleForm" ref="roleFormRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-drawer v-model="drawer" title="分配菜单">
    <el-tree
      :data="menuList"
      ref="tree"
      default-expand-all
      show-checkbox
      node-key="id"
      :default-checked-keys="seletcMenuList"
      :props="defaultProps"
    />

    <template #footer>
      <el-button @click="drawer = false">取消</el-button>
      <el-button type="primary" @click="updateRoleMenu">确定</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  reqRoleList,
  reqSaveOrUpdate,
  reqRemove,
  reqMenuList,
  reqUpdateMenu,
} from '@/api/auth/role'

let tree = ref()
let seletcMenuList = ref([])
let menuList = ref([])
let drawer = ref(false)
let roleFormRef = ref()
let page = ref(1)
let pageSize = ref(5)
let total = ref(20)
let keyWord = ref('')
let roleList = ref([])
let dialog = ref(false)
let roleForm = reactive({
  id: 0,
  roleName: '',
})
//树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}
//更新角色菜单
const updateRoleMenu = async () => {
  let ids = tree.value.getCheckedKeys()
  let ids2 = tree.value.getHalfCheckedKeys()
  let res = await reqUpdateMenu({
    roleId: roleForm.id,
    permissionIdList: [...ids, ...ids2],
  })
  if (res.code == 200) {
    ElMessage.success('更新菜单成功')
    window.location.reload()
  } else {
    ElMessage.error('更新菜单失败')
  }
  drawer.value = false
}
//分配菜单
const updateMenu = async (id) => {
  roleForm.id = id
  drawer.value = true
  let res = await reqMenuList(id)
  if (res.code == 200) {
    menuList.value = res.data
    seletcMenuList.value = seletList(menuList.value, [])
  }
}
//递归菜单方法
const seletList = (list, list2) => {
  list.forEach((item) => {
    if (item.select && item.children.length == 0) {
      //最后一层
      list2.push(item.id)
    }
    if (item.children.length != 0) {
      list2 = seletList(item.children, list2)
    }
  })
  return list2
}
//初始化
onMounted(() => {
  getRoleList()
})
//分页获取角色列表
const getRoleList = async (page1 = 1) => {
  page.value = page1
  let res = await reqRoleList(page.value, pageSize.value, keyWord.value)
  if (res.code == 200) {
    roleList.value = res.data.records
    total.value = res.data.total
  }
}
//pageSize改变
const handleSizeChange = () => {
  getRoleList()
}
//重置按钮
const reSet = () => {
  keyWord.value = ''
  getRoleList()
}
//编辑
const updateRole = (row) => {
  dialog.value = true
  Object.assign(roleForm, row)
  nextTick(() => {
    roleFormRef.value.clearValidate('roleName')
  })
}
//新增
const addRole = () => {
  dialog.value = true
  Object.assign(roleForm, {
    id: 0,
    roleName: '',
  })
  nextTick(() => {
    roleFormRef.value.clearValidate('roleName')
  })
}
//保存
const save = async () => {
  await roleFormRef.value.validate()
  let res = await reqSaveOrUpdate(roleForm)
  if (res.code == 200) {
    if (!roleForm.id) {
      ElMessage.success('新增成功')
      getRoleList()
    } else {
      ElMessage.success('编辑成功')
      getRoleList(page.value)
    }
  } else {
    ElMessage.error('操作失败')
  }
  dialog.value = false
}
//删除
// @ts-ignore
const remove = async (id) => {
  console.log(id)
  // @ts-ignore
  let res = await reqRemove(id)
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getRoleList(roleList.value.length > 1 ? page.value : page.value - 1)
  } else {
    ElMessage.error('删除失败')
  }
}
//校验字段
// @ts-ignore
const validateRoleName = (row, value, callback) => {
  if (value.trim().length < 3) {
    callback(new Error('角色名大于2位'))
  }
  callback()
}
//校验规则
let rules = reactive({
  roleName: [{ required: true, validator: validateRoleName, trigger: 'blur' }],
})
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
}
</style>
